---
import ItemContent from "@components/style/ItemContent.astro";
---
<section>
  <ItemContent>
    <h2 class="text-2xl font-bold mb-6 text-gray-800 dark:text-white">
      评论区
    </h2>
    <!-- 评论容器 - 后端将通过Thymeleaf渲染评论 -->
    <div
      class="comment-container space-y-6"
      th:with="data=${@commentTag.pageCommentTree('article_' + article.articleId, 'ARTICLE', themeName, 1, 10)}"
    >
      <!-- Thymeleaf将在这里渲染评论列表 -->
      <div
        th:each="comment, commentStat : ${data.rows}"
        th:id="'comment-'+${comment.commentId}"
        class="p-4 rounded-lg border border-gray-200 dark:border-gray-700 comment-item"
      >
        <!-- 评论头部 -->
        <div class="flex items-center mb-3">
          <img
            th:src="${comment.fromUser.avatar != null ? '/' + themeName + comment.fromUser.avatar : '/' + themeName + '/static/images/thumbs/default.jpg'}"
            th:alt="用户头像"
            class="w-10 h-10 rounded-full mr-3"
          />
          <div>
            <h3
              class="font-medium text-gray-800 dark:text-white"
              th:text="${comment.fromUser.nickName != null ? comment.fromUser.nickName : comment.fromUser.userName}"
            >
            </h3>
            <p
              class="text-sm text-gray-500 dark:text-gray-400"
              th:text="${comment.createTime + (comment.userSystem != null ? ' • ' + comment.userSystem + (comment.userBower != null ? ' • ' + comment.userBower : '') : '')}"
            >
            </p>
          </div>
        </div>

        <!-- 评论内容 -->
        <p
          class="text-gray-700 dark:text-gray-300 mb-3"
          th:utext="${comment.content}"
        >
        </p>

        <!-- 评论交互 -->
        <div class="flex items-center space-x-4 text-sm">
          <button
            class="flex items-center text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
            th:data-comment-id="${comment.commentId}"
            onclick="handleLike(this)"
          >
            <svg
              class="w-4 h-4 mr-1"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5"
              ></path>
            </svg>
            <span>点赞</span>
            <span
              class="ml-1 text-gray-400 dark:text-gray-500"
              th:text="${comment.likeCount}"></span>
          </button>
          <button
            class="flex items-center text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
            th:data-comment-id="${comment.commentId}"
            th:data-comment-from-username="${comment.fromUser.userName}"
            onclick="handleReplyForm(this)"
          >
            <svg
              class="w-4 h-4 mr-1"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"
              ></path>
            </svg>
            <span>回复</span>
          </button>
        </div>

        <!-- 嵌套回复 - 折叠式 -->
        <div class="mt-4 pl-4 border-l-2 border-gray-200 dark:border-gray-700 space-y-4" th:if="${comment.childPage != null and comment.childPage.rows != null and comment.childPage.rows.size() > 0}">
          <div class="child-comments-wrapper">
            <div class="flex items-center justify-between mb-2">
              <button 
                class="text-blue-500 hover:text-blue-600 text-sm flex items-center toggle-child-comments"
                th:data-parent-id="${comment.commentId}"
                th:data-total-pages="${comment.childPage.pages}"
                th:data-total-replies="${comment.childPage.total}"
                data-current-page="1"
                th:data-page-size="${comment.childPage.pageSize}"
                onclick="toggleChildComments(this)"
              >
                <svg class="w-4 h-4 mr-1 transform transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                </svg>
                <span th:text="'查看全部 ' + ${comment.childPage.total} + ' 条回复'"></span>
              </button>
            </div>
            
            <!-- 隐藏的评论列表容器 -->
            <div class="child-comments-container hidden space-y-4" th:id="'child-comments-' + ${comment.commentId}">
              <div th:each="reply, replyStat : ${comment.childPage.rows}" class="p-3 rounded-lg comment-item">
                <div class="flex items-center mb-2">
                  <img
                    th:src="${reply.fromUser.avatar != null ? '/' + themeName + reply.fromUser.avatar : '/' + themeName + '/static/images/thumbs/default.jpg'}"
                    th:alt="用户头像"
                    class="w-8 h-8 rounded-full mr-2"
                  />
                  <div>
                    <h4
                      class="font-medium text-sm text-gray-800 dark:text-white"
                      th:text="${reply.fromUser.nickName != null ? reply.fromUser.nickName : reply.fromUser.userName} + ${reply.replyUser != null ? ' 回复 ' + (reply.replyUser.nickName != null ? reply.replyUser.nickName : reply.replyUser.userName) : ''}"
                    >
                    </h4>
                    <p
                      class="text-xs text-gray-500 dark:text-gray-400"
                      th:text="${reply.createTime}"
                    >
                    </p>
                  </div>
                </div>
                <p
                  class="text-sm text-gray-700 dark:text-gray-300"
                  th:utext="${reply.content}"
                  th:id="'reply-content-' + ${reply.commentId}"
                >
                </p>
                <div class="flex items-center mt-2 space-x-3 text-xs">
                  <button
                    class="text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
                    th:data-comment-id="${reply.commentId}"
                    onclick="handleLike(this)"
                  >
                    点赞 (<span th:text="${reply.likeCount}"></span>)
                  </button>
                  <button
                    class="text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
                    th:data-comment-id="${reply.commentId}"
                    th:data-comment-from-username="${reply.fromUser.userName}"
                    onclick="handleReplyForm(this)"
                  >
                    回复
                  </button>
                </div>
              </div>
              
              <!-- 二级评论的加载更多按钮 -->
              <div class="mt-3 text-center" th:if="${comment.childPage.pageNum < comment.childPage.pages}">
                <button 
                  class="text-sm text-blue-500 hover:text-blue-600 load-more-child-comments"
                  th:data-parent-id="${comment.commentId}"
                  th:data-total-pages="${comment.childPage.pages}"
                  th:data-current-page="${comment.childPage.pageNum}"
                  th:data-page-size="${comment.childPage.pageSize}"
                  onclick="loadMoreChildComments(this)"
                >
                  加载更多回复
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 加载更多 -->
      <div
        class="mt-6 text-center load-more-container"
        th:classappend="${data.pageNum >= data.pages ? 'hidden' : ''}"
      >
        <button
          class="px-6 py-2 bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-white rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors load-more"
          th:data-total-pages="${data.pages}"
          th:data-current-page="${data.pageNum}"
          th:data-page-size="${data.pageSize}"
          onclick="loadMoreComments(this)"
        >
          加载更多评论
        </button>
      </div>
      <!-- 没有更多 -->
      <div
        class="mt-6 text-center load-complete-container"
        th:classappend="${data.pageNum >= data.pages ? '' : 'hidden'}"
      >
        <span class="text-gray-500 dark:text-gray-400 text-sm"
          th:text="${data.pageNum >= data.pages && data.rows.size() > 0 ? '已加载全部评论' : '目前还没有评论'}"></span
        >
      </div>
    </div>

    <!-- 评论表单 -->
    <div class="mt-8">
      <h3 class="text-xl font-semibold mb-4 text-gray-800 dark:text-white">
        发表评论
      </h3>
      <div class="p-4 rounded-lg">
        <div class="flex mb-4">
          <img
            src="/nice/static/images/thumbs/1.jpg"
            alt="当前用户头像"
            class="w-10 h-10 rounded-full mr-3"
          />
          <div class="flex-1">
            <div class="comment-form-container relative">
              <textarea
                class="w-full p-3 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 resize-none"
                rows="3"
                placeholder="写下你的评论..."
                id="comment-id-0"></textarea>
              <div class="flex justify-between items-center mt-3">
                <div class="flex items-center space-x-4">
                  <button
                    class="text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
                  >
                    <svg
                      class="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"></path>
                    </svg>
                  </button>
                  <button
                    class="text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
                  >
                    <svg
                      class="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
                      ></path>
                    </svg>
                  </button>
                </div>
                <button
                  id="submit-comment"
                  data-comment-id="0"
                  data-comment-from-username=""
                  class="px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                  onclick="handleReplySubmit(this)"
                >
                  发表评论
                </button>
              </div>
              <!-- 未登录遮罩层 -->
              <div sec:authorize="isAnonymous()" class="absolute inset-0 bg-black/30 dark:bg-black/50 rounded-lg flex items-center justify-center backdrop-blur-sm">
                <div class="text-center text-white px-6">
                  <p class="text-lg font-medium mb-2">请先登录后再评论</p>
                  <button onclick="handleLogin()" class="inline-block px-4 py-2 bg-blue-500 hover:bg-blue-600 rounded-lg text-white">立即登录</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </ItemContent>
</section>

<script>
  // 导入全局工具模块
  import { isUserLoggedIn, getThemeName, getUserName } from "@/utils/globalTools.js";
  // 导入Toast服务
  import "@components/common/toast";
  
  import { fetchDataWithPost, fetchDataWithGet } from "@/utils/fatch";
  window.addEventListener("DOMContentLoaded", function () {
    const recordType = "ARTICLE";
    const recordId = document.getElementById("articleId")?.value || "";
    // 使用全局工具获取主题名称
    const themeName = getThemeName();
    let leastReplyFormDom = null;
    // 点赞事件 - 重构版
    window.handleLike = async function (button) {
      try {
        // 检查用户是否登录
        if (!isUserLoggedIn()) {
          showToast("请先登录后再点赞", "warning");
          return;
        }
        
        // 防止重复点击
        button.disabled = true;
        const commentId = button.getAttribute("data-comment-id");
        
        if (!commentId) {
          showToast("评论ID不存在", "error");
          return;
        }
        
        // 显示加载中状态
        const originalContent = button.innerHTML;
        button.innerHTML = '<span class="loading-spinner"></span> 处理中...';
        
        const url = `/${themeName}/hand/comment/addCommentLike?commentId=${commentId}`;
        const response = await fetchDataWithPost(url, {});
        
        if (response && response.code === 200 && response.data) {
          const visible = response.data.visible;
          
          // 更新点赞数和按钮样式
          updateLikeCountAndStyle(button, visible);
          
          // 显示成功消息
          showToast(visible === 0 ? "点赞成功" : "取消点赞成功", "success");
        } else {
          // 显示错误消息
          const errorMsg = response ? (response.msg || "操作失败") : "网络错误";
          showToast(errorMsg, "error");
        }
      } catch (error) {
        showToast("操作失败，请稍后重试", "error");
      } finally {
        // 恢复按钮状态
        button.disabled = false;
      }
    };
    
    // 更新点赞数和按钮样式的辅助函数
    function updateLikeCountAndStyle(button, visible) {
      // 嵌套回复的点赞处理
      if (button.textContent.includes("点赞 (")) {
        const match = button.textContent.match(/点赞 \((\d+)\)/);
        if (match) {
          let currentCount = parseInt(match[1]);
          // 0代表点赞(增加1)，2代表取消点赞(减少1)
          currentCount += visible === 0 ? 1 : -1;
          button.textContent = `点赞 (${currentCount})`;
        }
      } else {
        // 普通评论的点赞处理
        let likeCountElement = button.querySelector("span:last-child");
        if (likeCountElement) {
          let currentCount = parseInt(likeCountElement.textContent) || 0;
          currentCount += visible === 0 ? 1 : -1;
          likeCountElement.textContent = currentCount;
        }
      }
      // 更新按钮样式
      if (visible === 0) {
        // 点赞状态
        button.classList.remove("text-gray-500", "dark:text-gray-400");
        button.classList.add("text-blue-500", "dark:text-blue-400");
      } else if (visible === 2) {
        // 取消点赞状态
        button.classList.remove("text-blue-500", "dark:text-blue-400");
        button.classList.add("text-gray-500", "dark:text-gray-400");
      }
    }
    
    // 显示提示消息的辅助函数
    function showToast(message, type = "info") {
      // 使用之前实现的Toast组件
      if (window.toast) {
        window.toast[type](message);
      } else {
        // 降级方案：如果Toast不可用，使用alert
        alert(message);
      }
    }
    
    // 添加简单的加载动画样式
    const style = document.createElement('style');
    style.textContent = `
      .loading-spinner {
        display: inline-block;
        width: 12px;
        height: 12px;
        border: 2px solid rgba(255, 255, 255, 0.3);
        border-radius: 50%;
        border-top-color: #fff;
        animation: spin 0.8s linear infinite;
        margin-right: 6px;
      }
      
      @keyframes spin {
        to { transform: rotate(360deg); }
      }
    `;
    document.head.appendChild(style);
    //评论框事件
    window.handleReplyForm = function (button) {
      // 找到父亲容器
      const parentContainer = button.closest(".comment-item");
      const commentId = button.getAttribute("data-comment-id");
      const parentCommentId = button.getAttribute("data-parent-id");
      const fromUsername = button.getAttribute("data-comment-from-username");
      if (!parentContainer) return;
      const replyFormDom = parentContainer.querySelector("#comment-item-form");
      
      // 查找当前打开评论框所在的容器，判断是否是父子关系
      const openContainer = leastReplyFormDom ? leastReplyFormDom.closest('.comment-item') : null;
      const isParentChildRelation = openContainer && openContainer !== parentContainer;
      
      // 如果是父子关系，直接移除打开的评论框并为当前点击的容器创建新的
      if (isParentChildRelation && replyFormDom) {
        leastReplyFormDom.remove();
        createReplyForm(button, commentId, parentCommentId, fromUsername);
        leastReplyFormDom = parentContainer.querySelector("#comment-item-form");
      }
      // 点击本身，本身已经打开，移除评论框
      else if (replyFormDom && leastReplyFormDom == replyFormDom) {
        leastReplyFormDom = null;
        replyFormDom.remove();
      }
      // 本身不存在，但有其他评论框打开
      else if (replyFormDom == null && leastReplyFormDom) {
        leastReplyFormDom.remove();
        createReplyForm(button, commentId, parentCommentId, fromUsername);
        leastReplyFormDom = parentContainer.querySelector("#comment-item-form");
      }
      // 创建新的评论框
      else {
        createReplyForm(button, commentId, parentCommentId, fromUsername);
        leastReplyFormDom = parentContainer.querySelector("#comment-item-form");
      }
    };

    // 创建新的回复表单的函数
    const createReplyForm = (
      button,
      commentId,
      parentCommentId,
      fromUsername,
    ) => {
      const replyFormHtml = isUserLoggedIn() ? `
        <div class="mt-3" id="comment-item-form">
          <div class="flex relative">
            <textarea 
              class="flex-1 p-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 resize-none"
              rows="2"
              placeholder="写下你的回复..."
              id="comment-id-${commentId}"
            ></textarea>
            <button class="ml-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors reply-submit" data-comment-from-username="${fromUsername}" data-comment-id="${commentId}" data-parent-id="${parentCommentId || ""}" onclick="handleReplySubmit(this)">
              回复
            </button>
          </div>
        </div>
      ` : `
        <div class="mt-3" id="comment-item-form">
          <div class="flex relative">
            <textarea 
              class="flex-1 p-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 resize-none"
              rows="2"
              placeholder="写下你的回复..."
              id="comment-id-${commentId}"
            ></textarea>
            <button class="ml-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors reply-submit" data-comment-from-username="${fromUsername}" data-comment-id="${commentId}" data-parent-id="${parentCommentId || ""}" onclick="handleReplySubmit(this)">
              回复
            </button>
            <!-- 未登录遮罩层 -->
            <div class="absolute inset-0 bg-black/30 dark:bg-black/50 rounded-lg flex items-center justify-center backdrop-blur-sm">
                <div class="text-center text-white px-4">
                  <p class="text-sm font-medium mb-1">请先登录后再回复</p>
                  <button onclick="handleLogin()" class="inline-block px-3 py-1 bg-blue-500 hover:bg-blue-600 rounded-lg text-white text-sm">立即登录</button>
                </div>
              </div>
          </div>
        </div>
      `;
      // 将表单插入到按钮后面
      button.parentElement.insertAdjacentHTML("afterend", replyFormHtml);
    };

    // 提交评论事件 - 重构版
    window.handleReplySubmit = async function (button) {
      try {
        // 检查用户是否登录
        if (!isUserLoggedIn()) {
          showToast("请先登录后再发表评论", "warning");
          return;
        }
        
        // 获取必要的参数
        const fromUsername = button.getAttribute("data-comment-from-username");
        const commentId = button.getAttribute("data-comment-id");
        const replyFormDom = document.getElementById(`comment-id-${commentId}`);
        
        // 参数校验
        if (!replyFormDom) {
          showToast("表单元素不存在", "error");
          return;
        }
        
        const commentContent = replyFormDom.value.trim();
        if (!commentContent) {
          showToast("请输入评论内容", "warning");
          replyFormDom.focus();
          return;
        }

        // 设置按钮为加载状态
        button.disabled = true;
        button.innerHTML = '<span class="loading-spinner"></span> 提交中...';
        
        // 构建请求数据
        const data = {
          recordId: recordId,
          content: commentContent,
          replyBy: fromUsername,
          parentId: commentId,
        };

        // 发送API请求
        const url = `/${themeName}/hand/comment/${recordType}/addComment`;
        const response = await fetchDataWithPost(url, data);

        // 处理响应结果
        if (response && response.code === 200) {
          // 成功处理
          handleSubmitSuccess(commentId, replyFormDom);
          showToast(commentId === "0" ? "评论发表成功" : "回复成功", "success");
        } else {
          // 显示错误消息
          const errorMsg = response ? (response.msg || "提交失败") : "网络错误";
          showToast(errorMsg, "error");
        }
      } catch (error) {
        showToast("提交失败，请稍后重试", "error");
      } finally {
        // 恢复按钮状态
        button.disabled = false;
        button.textContent = "回复";
      }
    };

    // 处理提交成功的辅助函数
    function handleSubmitSuccess(commentId, replyFormDom) {
      // 清除输入框内容
      replyFormDom.value = "";
      
      // 如果是回复（不是主评论），移除回复表单
      if (commentId !== "0" && leastReplyFormDom) {
        leastReplyFormDom.remove();
        leastReplyFormDom = null;
      }
    }

    //异步加载评论
    window.loadMoreComments = async function(button) {
      try {
        button.disabled = true;
        button.textContent = '加载中...';
        
        const currentPage = parseInt(button.getAttribute('data-current-page')) || 1;
        const totalPages = parseInt(button.getAttribute('data-total-pages')) || 1;
        const pageSize = parseInt(button.getAttribute('data-page-size')) || 10;
        const nextPage = currentPage + 1;
        
        // 找到加载更多容器
        const loadMoreContainer = button.closest('.load-more-container');
        // 找到或创建加载完成容器
        let loadCompleteContainer = loadMoreContainer ? loadMoreContainer.nextElementSibling : null;
        
        // 检查是否还有更多页
        if (nextPage > totalPages) {
          if (loadMoreContainer) {
            loadMoreContainer.classList.add('hidden');
          }
          if (loadCompleteContainer && loadCompleteContainer.classList.contains('load-complete-container')) {
            loadCompleteContainer.classList.remove('hidden');
          }
          return;
        }
        
        const url = `/${themeName}/api/comment/${recordType}/treePage?recordId=${recordId}&pageNum=${nextPage}&pageSize=${pageSize}`;
        const response = await fetchDataWithGet(url, { });
        
        if (response && response.code === 200 && response.data && response.data.rows) {
          const commentContainer = document.querySelector('.comment-container');
          
          if (!commentContainer || !loadMoreContainer) {
            throw new Error('无法找到必要的DOM元素');
          }
          
          response.data.rows.forEach(comment => {
            // 创建评论HTML
            const commentHtml = `
              <div id="comment-${comment.commentId}" class="p-4 rounded-lg border border-gray-200 dark:border-gray-700 comment-item">
                <!-- 评论头部 -->
                <div class="flex items-center mb-3">
                  <img 
                    src="${comment.fromUser.avatar != null ? '/' + themeName + comment.fromUser.avatar : '/' + themeName + '/static/images/thumbs/default.jpg'}" 
                    alt="用户头像" 
                    class="w-10 h-10 rounded-full mr-3"
                  />
                  <div>
                    <h3 class="font-medium text-gray-800 dark:text-white">
                      ${comment.fromUser.nickName != null ? comment.fromUser.nickName : comment.fromUser.userName}
                    </h3>
                    <p class="text-sm text-gray-500 dark:text-gray-400">
                      ${comment.createTime}${comment.userSystem != null ? ' • ' + comment.userSystem : ''}${comment.userBower != null ? ' • ' + comment.userBower : ''}
                    </p>
                  </div>
                </div>
                
                <!-- 评论内容 -->
                <p class="text-gray-700 dark:text-gray-300 mb-3" id="comment-content-${comment.commentId}">
                  ${comment.content}
                </p>
                
                <!-- 评论交互 -->
                <div class="flex items-center space-x-4 text-sm">
                  <button 
                    class="flex items-center text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
                    data-comment-id="${comment.commentId}"
                    onclick="handleLike(this)"
                  >
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5"></path>
                    </svg>
                    <span>点赞</span>
                    <span class="ml-1 text-gray-400 dark:text-gray-500">${comment.likeCount}</span>
                  </button>
                  <button 
                    class="flex items-center text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
                    data-comment-id="${comment.commentId}"
                    data-comment-from-username="${comment.fromUser.userName}"
                    onclick="handleReplyForm(this)"
                  >
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"></path>
                    </svg>
                    <span>回复</span>
                  </button>
                </div>
                
                <!-- 嵌套回复 -->
                <div class="mt-4 pl-4 border-l-2 border-gray-200 dark:border-gray-700 space-y-4" id="replies-container-${comment.commentId}">
                  ${renderChildComments(comment)}
                </div>
              </div>
            `;
            
            // 添加评论元素到容器中，在加载更多按钮前插入
            const tempContainer = document.createElement('div');
            tempContainer.innerHTML = commentHtml;
            const commentElement = tempContainer.firstElementChild;
            
            // 使用innerHTML设置评论内容，确保HTML标签正确渲染
            const contentElement = commentElement.querySelector(`#comment-content-${comment.commentId}`);
            if (contentElement) {
              contentElement.innerHTML = comment.content;
            }
            
            // 渲染嵌套回复的内容
            if (comment.childPage && comment.childPage.rows && comment.childPage.rows.length > 0) {
              const repliesContainer = commentElement.querySelector(`#replies-container-${comment.commentId}`);
              if (repliesContainer) {
                repliesContainer.innerHTML = renderChildComments(comment);
              }
            }
            
            // 插入到加载更多按钮之前
            commentContainer.insertBefore(commentElement, loadMoreContainer);
          });
          
          // 更新按钮状态和页码信息
          button.setAttribute('data-current-page', nextPage);
          
          // 如果已经加载完所有页，隐藏加载更多按钮，显示加载完成提示
          if (nextPage >= totalPages) {
            if (loadMoreContainer) {
              loadMoreContainer.classList.add('hidden');
            }
            if (loadCompleteContainer && loadCompleteContainer.classList.contains('load-complete-container')) {
              loadCompleteContainer.classList.remove('hidden');
            }
          }
        } else {
          alert('加载评论失败：' + (response ? (response.msg || '未知错误') : '未知错误'));
        }
      } catch (error) {
        console.error('加载更多评论时发生错误:', error);
        alert('加载更多评论时发生错误：' + error.message);
      } finally {
        button.disabled = false;
        button.textContent = '加载更多评论';
      }
    };
    
    // 渲染子评论的辅助函数
    function renderChildComments(parentComment) {
      if (!parentComment.childPage || !parentComment.childPage.rows || parentComment.childPage.rows.length === 0) {
        return '';
      }
      
      const totalReplies = parentComment.childPage.total;
      const hasMorePages = parentComment.childPage.pageNum < parentComment.childPage.pages;
      
      // 返回折叠的评论容器
      return `
        <div class="child-comments-wrapper">
          <div class="flex items-center justify-between mb-2">
            <button 
              class="text-blue-500 hover:text-blue-600 text-sm flex items-center toggle-child-comments"
              data-parent-id="${parentComment.commentId}"
              data-total-pages="${parentComment.childPage.pages}"
              data-total-replies="${totalReplies}"
              data-current-page="1"
              data-page-size="${parentComment.childPage.pageSize}"
              onclick="toggleChildComments(this)"
            >
              <svg class="w-4 h-4 mr-1 transform transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
              </svg>
              查看全部 ${totalReplies} 条回复
            </button>
          </div>
          
          <!-- 隐藏的评论列表容器 -->
          <div class="child-comments-container hidden space-y-4" id="child-comments-${parentComment.commentId}">
            ${parentComment.childPage.rows.map(reply => {
              const replyUserText = reply.replyUser ? 
                ` 回复 ${reply.replyUser.nickName != null ? reply.replyUser.nickName : reply.replyUser.userName}` : 
                '';
              
              return `
                <div class="p-3 rounded-lg comment-item">
                  <div class="flex items-center mb-2">
                    <img 
                      src="${reply.fromUser.avatar != null ? '/' + themeName + reply.fromUser.avatar : '/' + themeName + '/static/images/thumbs/default.jpg'}" 
                      alt="用户头像" 
                      class="w-8 h-8 rounded-full mr-2"
                    />
                    <div>
                      <h4 class="font-medium text-sm text-gray-800 dark:text-white">
                        ${reply.fromUser.nickName != null ? reply.fromUser.nickName : reply.fromUser.userName}${replyUserText}
                      </h4>
                      <p class="text-xs text-gray-500 dark:text-gray-400">
                        ${reply.createTime}
                      </p>
                    </div>
                  </div>
                  <p class="text-sm text-gray-700 dark:text-gray-300" id="reply-content-${reply.commentId}">
                    ${reply.content}
                  </p>
                  <div class="flex items-center mt-2 space-x-3 text-xs">
                    <button 
                      class="text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
                      data-comment-id="${reply.commentId}"
                      onclick="handleLike(this)"
                    >
                      点赞 (<span>${reply.likeCount}</span>)
                    </button>
                    <button 
                      class="text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
                      data-comment-id="${reply.commentId}"
                      data-comment-from-username="${reply.fromUser.userName}"
                      onclick="handleReplyForm(this)"
                    >
                      回复
                    </button>
                  </div>
                </div>
              `;
            }).join('')}
            
            <!-- 二级评论的加载更多按钮 -->
            ${hasMorePages ? `
              <div class="mt-3 text-center">
                <button 
                  class="text-sm text-blue-500 hover:text-blue-600 load-more-child-comments"
                  data-parent-id="${parentComment.commentId}"
                  data-total-pages="${parentComment.childPage.pages}"
                  data-current-page="${parentComment.childPage.pageNum}"
                  data-page-size="${parentComment.childPage.pageSize}"
                  onclick="loadMoreChildComments(this)"
                >
                  加载更多回复
                </button>
              </div>
            ` : ''}
          </div>
        </div>
      `;
    }
    
    // 切换子评论显示/隐藏
    window.toggleChildComments = function(button) {
      const parentId = button.getAttribute('data-parent-id');
      const commentsContainer = document.getElementById(`child-comments-${parentId}`);
      const svg = button.querySelector('svg');
      
      if (commentsContainer) {
        commentsContainer.classList.toggle('hidden');
        svg.classList.toggle('rotate-180');
        
        // 更新按钮文本
        if (commentsContainer.classList.contains('hidden')) {
          const totalReplies = button.getAttribute('data-total-replies');
          button.innerHTML = `
            <svg class="w-4 h-4 mr-1 transform transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
            </svg>
            查看全部 ${totalReplies} 条回复
          `;
          button.setAttribute('onclick', 'toggleChildComments(this)');
        } else {
          button.innerHTML = `
            <svg class="w-4 h-4 mr-1 transform transition-transform duration-300 rotate-180" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
            </svg>
            收起回复
          `;
          button.setAttribute('onclick', 'toggleChildComments(this)');
        }
      }
    };
    
    // 加载更多子评论
    window.loadMoreChildComments = async function(button) {
      try {
        button.disabled = true;
        button.textContent = '加载中...';  
        const parentId = button.getAttribute('data-parent-id');
        const currentPage = parseInt(button.getAttribute('data-current-page')) || 1;
        const totalPages = parseInt(button.getAttribute('data-total-pages')) || 1;
        const pageSize = parseInt(button.getAttribute('data-page-size')) || 10;
        const nextPage = currentPage + 1;
        if (nextPage > totalPages) {
          return;
        }
        
        // 调用后端API获取更多二级评论
        const url = `/${themeName}/api/comment/${recordType}/secondLeavePage?parentId=${parentId}&pageNum=${nextPage}&pageSize=${pageSize}`;
        const response = await fetchDataWithGet(url, {});
        
        if (response && response.code === 200 && response.data && response.data.rows) {
          const commentsContainer = document.getElementById(`child-comments-${parentId}`);
          
          if (!commentsContainer) {
            throw new Error('无法找到评论容器');
          }
          
          // 找到加载更多按钮的位置，在其前插入新评论
          const loadMoreButtonContainer = button.closest('div');
          
          // 渲染新的评论
          response.data.rows.forEach(reply => {
            const replyUserText = reply.replyUser ? 
              ` 回复 ${reply.replyUser.nickName != null ? reply.replyUser.nickName : reply.replyUser.userName}` : 
              '';
            
            const replyHtml = `
              <div class="p-3 rounded-lg comment-item">
                <div class="flex items-center mb-2">
                  <img 
                    src="${reply.fromUser.avatar != null ? '/' + themeName + reply.fromUser.avatar : '/' + themeName + '/static/images/thumbs/default.jpg'}" 
                    alt="用户头像" 
                    class="w-8 h-8 rounded-full mr-2"
                  />
                  <div>
                    <h4 class="font-medium text-sm text-gray-800 dark:text-white">
                      ${reply.fromUser.nickName != null ? reply.fromUser.nickName : reply.fromUser.userName}${replyUserText}
                    </h4>
                    <p class="text-xs text-gray-500 dark:text-gray-400">
                      ${reply.createTime}
                    </p>
                  </div>
                </div>
                <p class="text-sm text-gray-700 dark:text-gray-300" id="reply-content-${reply.commentId}">
                  ${reply.content}
                </p>
                <div class="flex items-center mt-2 space-x-3 text-xs">
                  <button 
                    class="text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
                    data-comment-id="${reply.commentId}"
                    onclick="handleLike(this)"
                  >
                    点赞 (<span>${reply.likeCount}</span>)
                  </button>
                  <button 
                    class="text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
                    data-comment-id="${reply.commentId}"
                    data-comment-from-username="${reply.fromUser.userName}"
                    onclick="handleReplyForm(this)"
                  >
                    回复
                  </button>
                </div>
              </div>
            `;
            
            // 在加载更多按钮前插入新评论
            commentsContainer.insertAdjacentHTML('beforeend', replyHtml);
          });
          
          // 更新按钮状态和页码信息
          button.setAttribute('data-current-page', nextPage);
          
          // 如果已经加载完所有页，隐藏加载更多按钮
          if (nextPage >= totalPages) {
            loadMoreButtonContainer.classList.add('hidden');
          }
        } else {
          alert('加载评论失败：' + (response ? (response.msg || '未知错误') : '未知错误'));
        }
      } catch (error) {
        console.error('加载更多子评论时发生错误:', error);
        alert('加载更多子评论时发生错误：' + error.message);
      } finally {
        button.disabled = false;
        button.textContent = '加载更多回复';
      }
    };
});
</script>
